/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.map.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.lxk.map.domain.bo.MapInfoImportBo;
import com.lxk.map.domain.vo.NewMapInfoVo;
import com.lxk.map.gd.api.GdApi;
import com.lxk.map.gd.model.GdGeoResp;
import com.lxk.map.gd.model.GeoAddressReq;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.BeanCopyUtils;
import org.dromara.common.excel.utils.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 地图API
 *
 * @author heyi
 * 2024/8/5
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/map")
public class MapController {

    private static final Logger log = LoggerFactory.getLogger(MapController.class);
    private final GdApi gdApi;

    /**
     * 根据地址自动解析经纬度
     *
     * @param address
     * @return
     */
    @PostMapping("parseMapInfo")
    public R<NewMapInfoVo> parseMapInfo(String address) {
        MapInfoImportBo query = new MapInfoImportBo();
        query.setAddress(address);
        NewMapInfoVo newMapInfoVo = queryGeoInfo(query);
        return R.ok(newMapInfoVo);
    }

    /**
     * 导出根据地址自动解析经纬度，https://wia.amap.com/
     */
    @PostMapping(value = "parse", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void parseMapInfo(@RequestPart("file") MultipartFile file, HttpServletResponse response) throws IOException {
        String md5 = DigestUtil.md5Hex(file.getInputStream());
        log.info("{}", md5);
        List<MapInfoImportBo> mapInfoImportBoList = ExcelUtil.importExcel(file.getInputStream(), MapInfoImportBo.class);
        List<NewMapInfoVo> infoVoList = mapInfoImportBoList.stream().limit(1).filter(item -> StrUtil.isNotBlank(item.getAddress())).map(this::queryGeoInfo).filter(Objects::nonNull).toList();
        ExcelUtil.exportExcel(infoVoList, "标记位置", NewMapInfoVo.class, response);
    }

    private NewMapInfoVo queryGeoInfo(MapInfoImportBo item) {
        try {
            GeoAddressReq req = new GeoAddressReq();
            String name = item.getName();
            req.setAddress(item.getAddress());
            List<GdGeoResp.GeocodesModel> geocodes = gdApi.geo(req).getGeocodes();
            if (CollUtil.isNotEmpty(geocodes)) {
                GdGeoResp.GeocodesModel geocodesModel = geocodes.get(0);
                String location = geocodesModel.getLocation();
                NewMapInfoVo newMapInfoVo = BeanCopyUtils.copy(geocodesModel, NewMapInfoVo.class);
                newMapInfoVo.setAddress(geocodesModel.getFormattedAddress());
                newMapInfoVo.setName(StrUtil.blankToDefault(name, "无门店名"));
                List<String> locationList = StrUtil.split(location, ",");
                if (CollUtil.isNotEmpty(locationList)) {
                    newMapInfoVo.setLongitude(locationList.get(0));
                    newMapInfoVo.setLatitude(locationList.get(1));
                }
                newMapInfoVo.setDesc(item.getPhone());
                return newMapInfoVo;
            }
        } catch (Exception e) {
            log.error("获取地址发生异常,请求参数{}", JSONUtil.toJsonPrettyStr(item), e);
        }
        return null;
    }
}
